#include <iostream>
#include "tinyxml.h"

int main() {
    // 创建 XML 文档
    TiXmlDocument doc;
    
    // 创建根节点
    TiXmlElement* root = new TiXmlElement("Root");
    doc.LinkEndChild(root);

    // 创建子节点
    TiXmlElement* child1 = new TiXmlElement("Child1");
    child1->SetAttribute("attr1", "value1");
    child1->LinkEndChild(new TiXmlText("Text for Child1"));
    root->LinkEndChild(child1);

    // 创建另一个子节点
    TiXmlElement* child2 = new TiXmlElement("Child2");
    child2->SetAttribute("attr2", "value2");
    child2->LinkEndChild(new TiXmlText("Text for Child2"));
    root->LinkEndChild(child2);

    // 保存 XML 文档到文件
    if (doc.SaveFile("example.xml")) {
        std::cout << "XML file saved successfully." << std::endl;
    } else {
        std::cerr << "Failed to save XML file." << std::endl;
        return -1;
    }

    // 读取 XML 文件并输出内容
    TiXmlDocument doc2("example.xml");
    if (doc2.LoadFile()) {
        std::cout << "Loaded XML file successfully." << std::endl;
        TiXmlElement* root2 = doc2.FirstChildElement("Root");
        if (root2) {
            for (TiXmlElement* elem = root2->FirstChildElement(); elem; elem = elem->NextSiblingElement()) {
                std::cout << "Element: " << elem->Value() << std::endl;
                TiXmlAttribute* attr = elem->FirstAttribute();
                while (attr) {
                    std::cout << "Attribute: " << attr->Name() << " = " << attr->Value() << std::endl;
                    attr = attr->Next();
                }
                TiXmlText* text = elem->FirstChild()->ToText();
                if (text) {
                    std::cout << "Text: " << text->Value() << std::endl;
                }
            }
        } else {
            std::cerr << "Root element not found." << std::endl;
        }
    } else {
        std::cerr << "Failed to load XML file." << std::endl;
        return -1;
    }

    // 修改 XML 文件中的内容
    TiXmlElement* child3 = new TiXmlElement("Child3");
    child3->LinkEndChild(new TiXmlText("Text for Child3"));
    root->LinkEndChild(child3);

    if (doc.SaveFile("example_modified.xml")) {
        std::cout << "Modified XML file saved successfully." << std::endl;
    } else {
        std::cerr << "Failed to save modified XML file." << std::endl;
        return -1;
    }

    return 0;
}
